<?php

namespace App\Services\Admin;

use App\Models\Notice;

class NoticeService
{
    protected $noticeModel;

    public function __construct(Notice $noticeModel)
    {
        $this->noticeModel = $noticeModel;
    }

    /**
     * 获取未读消息列表
     * @param int $adminId 管理员ID
     * @param array $params 查询参数
     * @return array
     */
    public function getUnreadList(int $adminId, array $params): array
    {
        // 添加管理员ID条件，查询该管理员的消息和全局消息
        $params['current_admin_id'] = $adminId;
        // 只查询未读状态的消息
        $params['status'] = Notice::STATUS_UNREAD;
        // 只获取今天的消息
        $params['start_time'] = date('Y-m-d 00:00:00');
        $params['end_time'] = date('Y-m-d 23:59:59');

        $fields = ['id', 'title', 'content', 'url', 'created_at'];
        $result = $this->noticeModel->search($params, $fields);

        return $result;
    }

    /**
     * 标记消息为已读
     * @param int $id 消息ID
     * @return array
     */
    public function markAsRead(int $id): array
    {
        $rows = $this->noticeModel->modify($id, ['status' => Notice::STATUS_READ]);
        return ['affected_rows' => $rows];
    }

    /**
     * 批量标记消息为已读
     * @param array $ids 消息ID数组
     * @return array
     */
    public function markMultipleAsRead(array $ids): array
    {
        $rows = $this->noticeModel->updateBy(['id' => $ids], ['status' => Notice::STATUS_READ]);
        return ['affected_rows' => $rows];
    }

    /**
     * 创建通知
     * @param string $title 通知标题
     * @param string $content 通知内容
     * @param int $adminId 管理员ID，0表示全局通知
     * @param string $url 跳转链接
     * @return array
     */
    public function createNotice(string $title, string $content, int $adminId = 0, string $url = ''): array
    {
        $data = [
            'title' => $title,
            'content' => $content,
            'admin_id' => $adminId,
            'url' => $url,
            'status' => Notice::STATUS_UNREAD,
            'created_at' => time(),
            'updated_at' => time()
        ];

        $id = $this->noticeModel->create($data);
        return ['id' => $id];
    }

    /**
     * 批量创建通知
     * @param array $notices 通知数据数组
     * @return array
     */
    public function createMultipleNotices(array $notices): array
    {
        $createdCount = 0;
        foreach ($notices as $notice) {
            $data = [
                'title' => $notice['title'],
                'content' => $notice['content'],
                'admin_id' => $notice['admin_id'] ?? 0,
                'url' => $notice['url'] ?? '',
                'status' => Notice::STATUS_UNREAD,
                'created_at' => time(),
                'updated_at' => time()
            ];

            $this->noticeModel->create($data);
            $createdCount++;
        }

        return ['created_count' => $createdCount];
    }
}
